package main

import (
	"errors"
	"fmt"
	"gitee.com/simple-set/simple.io/src/event"
	"gitee.com/simple-set/simple.io/src/process/http"
	"gitee.com/simple-set/simple.proxy/src/config"
	"gitee.com/simple-set/simple.proxy/src/handler"
	"log/slog"
)

type Server struct {
	bootServer *event.BootServer
}

func NewServer() *Server {
	return &Server{bootServer: event.NewBootServer()}
}

// 注册处理器, 根据代理模式不同, 分别注册对应的处理器
func (s *Server) register() error {
	switch config.Config.ProxyMode {
	case config.Config.Http.Name:
		s.bootServer.Register(http.NewRequestProcess())
		s.bootServer.Register(handler.NewHttpProxy())
	case config.Config.Socks.Name:
		s.bootServer.Register(handler.SocksProcessFactory())
	case config.Config.Tcp.Name:
		s.bootServer.Register(handler.NewTcpProxy())
	default:
		return errors.New("Unsupported service mode: " + config.Config.ProxyMode)
	}
	slog.Info(fmt.Sprintf("%s proxy mode", config.Config.ProxyMode))
	return nil
}

// 启动监听
func (s *Server) listen() error {
	listenAddrAndPort := fmt.Sprintf("%s:%d", config.Config.ListenAddr, config.Config.Port)
	return s.bootServer.ListenTcp(listenAddrAndPort)
}

func (s *Server) start() error {
	if err := s.register(); err != nil {
		return err
	}
	return s.listen()
}
